/**
 * user.js
 * @author Baip 125618036@qq.com
 */
var User = require('../../models/user');
var common = require('../../common/common');


exports.index = function(req, res){
	res.send('home page');
	res.render('index', { title: '首页' });
}

/**
 * 用户注册
 */
exports.reg = function (req, res){
	res.render('user/reg', { title: '用户注册' });
}

exports.signup = function(req, res){
	res.render('user/signup', {'title':'用户注册'});
}

/**
 * 用户注册提交信息
 */
exports.reged = function (req, res){
	var _user = req.body.user;
	if ( _user == 'undefined' ) {
		res.send( common.returnAjax(0,'参数错误','') );
	}
	//为了保证用户的唯一性。判断是否存在当前注册的用户名
	User.findById({"$or":[{'username' : _user.username},{'email':_user.email}]},{username:1}, function(err, user){
		if ( err ) {
			res.send(common.retunAjax(0,'系统错误',''));
		}
		if ( user ) {
			res.send(common.returnAjax(0,'用户名或邮箱已经存在',''));
		}else{
			user = new User(_user);
			user.save(function(err, user){
				if ( err ) {
					res.send(common.returnAjax(0,'注册失败',''));
				}else{
					res.send(common.returnAjax(1,'注册成功','/'));
				}
			})
		}
	})
}

/**
 * 用户登录
 */
exports.login = function(req, res){
	res.render('user/login', {title:'用户登录'});
}
/**
 * 用户登录
 */
exports.signin = function(req, res){
	res.render('user/signin', {'title':'用户登录'});
}

/**
 * 用户登录验证
 */
exports.logined = function(req, res){
	var _user = req.body.user;
	var username = _user.username;
	var password = _user.password;

	User.findById({username : username}, {'_id':1,'username':1,'password':1,'email':1,'role':1},function(err, user){
		if ( err ) {
			res.send( common.returnAjax(0, err,'') );
		}
		//如果不存在数据
		if ( !user ) {
			res.send( common.returnAjax(0, '登录失败', '/') ) ;
		}else{
			//如果存在数据进行验证
			var md5_password = common.md5(password);
			if ( user.password != md5_password ) {
				res.send( common.returnAjax(0, '密码不正确'),'' );
			}else{
				//更新登录信息到数据
				var date = new Date();
				user.last_login_time = date.getTime();
				user.last_login_ip   = req.ip;
				user.save();
				//将用户信息记录到session
				req.session.user = {username:user.username,email:user.email,userid:user._id.toString(),role:user.role};
				res.send(common.returnAjax(1, '登录成功', '/'));
			}
		}
	})
}

/**
 * 退出登录
 */
exports.logout = function(req, res){
	delete req.session.user;
	res.redirect('/');
}


/**
 * 验证后台权限登录
 */
//验证是否登录
exports.signinRequired = function(req, res, next){
	var user = req.session.user;
	console.log(user);
	if (!user) {
		return res.redirect('/user/signin');
	}
	next();
}
//验证是否有权限
exports.adminRequired = function(req, res, next){
	var user = req.session.user;
	//如果用户角色id小于50的不为后台管理员
	if ( user.role < 50 ) {
		return res.redirect('/user/signin');
	}
	next();
}
